Popular Searches
Popular Course Categories
Popular Courses

Preventing Default Browser Behaviour

Preventing Default Browser Behaviour

React Events and Conditional Rendering

Preventing Default Browser Behaviour in React JS

Preventing Default Browser Behaviour is an important concept in React JS that allows developers to stop the browser's built-in actions when necessary. The event.preventDefault() method is commonly used to prevent automatic page reloads during form submission, stop link navigation, and control other cancelable browser actions. It allows developers to handle events using JavaScript and React event handlers.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.


1. What Is Default Browser Behaviour?

Default browser behaviour refers to the built-in action a web browser performs when a particular event occurs. These actions are provided by the browser without requiring developers to write additional JavaScript code.

For example, clicking a link normally navigates to another URL, submitting a traditional HTML form can reload the page, and clicking a checkbox normally changes its checked state.

Examples of Default Browser Behaviour

HTML Element or Action Default Behaviour
Form submission Submits form data and may navigate to a URL or reload the page.
Anchor link Navigates to the URL specified by its href attribute.
Checkbox Toggles between checked and unchecked.
Radio button Selects the radio option when clicked.
Browser context menu Usually opens when the user right-clicks.
Keyboard input May insert text or perform the browser's standard keyboard action.

2. What Is event.preventDefault() in React?

event.preventDefault() is a method used to cancel the default action associated with a cancelable event. In React, it is commonly called inside an event handler when the application needs to manage the interaction itself.

For example, when a user submits a form, the browser may perform its default submission behaviour. Calling event.preventDefault() prevents that default action, allowing the React application to process the form data without the usual browser navigation or page reload.

Syntax

function handleEvent(event) {
  event.preventDefault();
}

Explanation:

  • event represents the event object received by the handler.
  • preventDefault() cancels the event's default browser action when that action is cancelable.
  • The remaining JavaScript code in the handler can continue executing.

3. Why Is Preventing Default Behaviour Important?

  • Preventing unwanted page reloads: Handle form submissions without the browser's traditional reload behaviour.
  • Custom form processing: Validate and process form values using React and JavaScript.
  • Controlling navigation: Stop a link's default navigation when a different interaction is required.
  • Custom interactions: Replace certain browser actions with application-specific behaviour.
  • Improved user experience: Avoid unnecessary navigation when an interaction can be handled in the current interface.
  • Event control: Decide how a cancelable event should be handled by the application.

4. Preventing Default Behaviour in Form Submission

One of the most common uses of event.preventDefault() in React is handling form submissions. Without preventing the default action, a traditional form submission may navigate away from the current page or reload it.

Example Without preventDefault()

function ContactForm() {
  function handleSubmit() {
    alert("Form submitted!");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="username" />
      <button type="submit">Submit</button>
    </form>
  );
}
export default ContactForm;

In this example, the browser's default form submission is not prevented. The alert may appear, but the browser can then continue with its default submission behaviour.

Example With preventDefault()

function ContactForm() {
  function handleSubmit(event) {
    event.preventDefault();
    alert("Form submitted without page reload!");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="username" />
      <button type="submit">Submit</button>
    </form>
  );
}
export default ContactForm;

Explanation: The event handler receives the form submission event, prevents the browser's default action, and displays the message without performing the traditional form submission.


5. Preventing Default Behaviour in Anchor Links

Anchor elements use the href attribute to navigate to another page, URL, or location. Sometimes, an application needs to intercept a link click and execute custom logic instead of following the link immediately.

Example:

function App() {
  function handleClick(event) {
    event.preventDefault();
    alert("Default link navigation prevented!");
  }

  return (
    <a href="https://example.com" onClick={handleClick}>
      Click Here
    </a>
  );
}
export default App;

When the link is clicked, the browser does not navigate to the specified URL because the handler prevents the default navigation.

Important: Do not prevent link navigation unnecessarily. Use a normal anchor for external websites, and use appropriate routing links for navigation within a React application.


6. Preventing Default Behaviour in Checkbox Events

A checkbox normally changes its checked state when clicked. In certain situations, a developer may need to prevent that default toggle action.

Example:

function App() {
  function handleCheckboxClick(event) {
    event.preventDefault();
    console.log("Checkbox default toggle prevented.");
  }

  return (
    <label>
      <input
        type="checkbox"
        onClick={handleCheckboxClick}
      />
      Accept Terms
    </label>
  );
}
export default App;

In this example, the browser's normal checkbox toggle is canceled by the click handler.

Note: This is mainly a demonstration of the method. In production forms, use controlled checkbox state or the disabled attribute when appropriate instead of preventing checkbox interaction without a clear reason.


7. Preventing Default Behaviour in Keyboard Events

Keyboard events can trigger default browser actions. For example, pressing certain keys may insert text, activate controls, or trigger browser shortcuts. For a cancelable keyboard event, event.preventDefault() can prevent its default action.

Example:

function App() {
  function handleKeyDown(event) {
    if (event.key === "Enter") {
      event.preventDefault();
      console.log("Default Enter key action prevented.");
    }
  }

  return (
    <input
      type="text"
      placeholder="Press Enter"
      onKeyDown={handleKeyDown}
    />
  );
}
export default App;

This example prevents the default action associated with the Enter key event when that action is cancelable. The exact effect depends on the focused element and browser behaviour.


8. Understanding the Event Object

React event handlers receive an event object that provides information about the event and methods for controlling its behaviour. The event object is often named event or e.

Example:

function App() {
  function handleClick(event) {
    console.log("Event type:", event.type);
    console.log("Target element:", event.target);
    console.log("Current target:", event.currentTarget);
    console.log("Default prevented:", event.defaultPrevented);

    event.preventDefault();
  }

  return (
    <a href="https://example.com" onClick={handleClick}>
      Open Link
    </a>
  );
}
export default App;

Important Event Properties

Property or Method Description
event.type Identifies the event type, such as click or submit.
event.target Identifies the element where the event originated.
event.currentTarget Identifies the element whose handler is currently running.
event.preventDefault() Prevents the default action of a cancelable event.
event.defaultPrevented Indicates whether the default action has been prevented.
event.stopPropagation() Stops the event from propagating to ancestor handlers.

9. Difference Between preventDefault() and stopPropagation()

Both methods control event behaviour, but they solve different problems. They should not be treated as interchangeable.

preventDefault() stopPropagation()
Prevents the default browser action associated with a cancelable event. Stops the event from propagating to ancestor handlers.
Used to stop actions such as form submission navigation or link navigation. Used to prevent parent event handlers from responding to a bubbling event.
Does not automatically stop event propagation. Does not automatically prevent the browser's default action.
Example: event.preventDefault() Example: event.stopPropagation()

Example of Both Methods

function App() {
  function handleParentClick() {
    console.log("Parent clicked");
  }

  function handleChildClick(event) {
    event.preventDefault();
    event.stopPropagation();
    console.log("Child clicked");
  }

  return (
    <div onClick={handleParentClick}>
      <a href="https://example.com" onClick={handleChildClick}>
        Click Child Link
      </a>
    </div>
  );
}
export default App;

When the link is clicked, its default navigation is prevented, and the click event does not bubble to the parent div's handler.


10. Handling Form Data After Preventing Default Behaviour

Preventing default form submission allows the application to process the entered data in JavaScript. FormData can collect values from form controls that have name attributes.

Example:

function SearchForm() {
  function handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData(event.currentTarget);
    const searchTerm = formData.get("search");

    console.log("Search term:", searchTerm);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="search"
        placeholder="Enter search term"
      />
      <button type="submit">Search</button>
    </form>
  );
}
export default SearchForm;

Explanation:

  • The form uses the onSubmit event handler.
  • event.preventDefault() prevents the browser's default submission action.
  • FormData reads the values of named form controls.
  • The search term is retrieved using formData.get("search").
  • The application can then process the value or send it to a server.

Important: Preventing default behaviour does not automatically send data to a server or save it to a database.


11. Practical Example: React Registration Form

This practical example demonstrates how to prevent default browser behaviour while processing registration form data.

RegistrationForm.jsx

import { useState } from "react";

function RegistrationForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");

  function handleSubmit(event) {
    event.preventDefault();

    if (!name.trim() || !email.trim()) {
      setMessage("Please complete all fields.");
      return;
    }

    setMessage(`Registration details received for ${name}.`);
  }

  return (
    <div>
      <h2>Registration Form</h2>
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">Name:</label>
        <input
          id="name"
          value={name}
          onChange={(event) => setName(event.target.value)}
          required
        />

        <label htmlFor="email">Email:</label>
        <input
          id="email"
          type="email"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          required
        />

        <button type="submit">Register</button>
      </form>

      {message && <p role="status">{message}</p>}
    </div>
  );
}
export default RegistrationForm;

How It Works

  • useState stores the name, email, and message values.
  • onChange handlers update the controlled input values.
  • onSubmit calls handleSubmit when the form is submitted.
  • event.preventDefault() prevents the browser's default submission action.
  • The handler checks the required values and displays a message.

This is a frontend demonstration only. A real registration system would need appropriate backend processing and server-side validation.


12. When Should You Use preventDefault()?

Use preventDefault() when an event has a default browser action that conflicts with the intended application behaviour and the event is cancelable.

  • When handling form submission in JavaScript without a traditional page reload.
  • When intercepting an anchor link to perform a custom action.
  • When canceling a checkbox or keyboard action for a specific, justified interaction.
  • When implementing custom drag-and-drop behaviour that requires preventing a browser default action.
  • When building interactive components that need to replace a specific browser action.

When Should You Avoid It?

  • Do not prevent default behaviour if the browser's normal action is appropriate.
  • Do not cancel link navigation when the link should open normally.
  • Do not block keyboard or form interactions in ways that reduce accessibility.
  • Do not use it as a substitute for proper form validation.
  • Do not assume it works on every event; non-cancelable events cannot have their default action canceled this way.

13. Common Mistakes When Using preventDefault()

  • Forgetting the event parameter: The handler needs the event object to call event.preventDefault().
  • Calling it outside an event handler: It must be called with the relevant event object when handling the event.
  • Confusing it with stopPropagation(): Preventing the default action does not stop the event from bubbling.
  • Expecting automatic data storage: The method does not save or transmit form data by itself.
  • Using it unnecessarily: Canceling default actions without a clear reason can break expected browser behaviour.
  • Ignoring native validation: Browser validation may prevent an invalid form from submitting before the submit event is dispatched.
  • Assuming every event is cancelable: Calling preventDefault() has no effect when the event cannot be canceled.
  • Forgetting to implement the replacement action: If the default action is prevented, the application should perform the intended action where necessary.

14. Best Practices

  • Use descriptive event handler names such as handleSubmit and handleLinkClick.
  • Call event.preventDefault() only when necessary.
  • Keep form validation separate from data submission logic when it improves code clarity.
  • Use controlled components when form values need to stay synchronized with React state.
  • Preserve normal browser navigation and keyboard behaviour wherever possible.
  • Use semantic HTML elements such as form, button, and a.
  • Provide clear feedback after custom form processing.
  • Validate submitted data on the server when interacting with a backend.
  • Test the expected behaviour in relevant browsers and interaction scenarios.

15. Interview Questions and Answers

Q1. What is preventDefault() in React?

It is a method on the event object that prevents the default browser action associated with a cancelable event.

Q2. Why is preventDefault() used in forms?

It allows a React application to handle form submission in JavaScript without the browser performing its usual default submission action.

Q3. Does preventDefault() stop event propagation?

No. It prevents the default action but does not automatically stop the event from bubbling to parent handlers.

Q4. What is the difference between preventDefault() and stopPropagation()?

preventDefault() cancels the default browser action, while stopPropagation() prevents the event from reaching ancestor event handlers.

Q5. Can preventDefault() stop link navigation?

Yes. When called in a suitable click handler, it can prevent the anchor's default navigation.

Q6. Does preventDefault() save form data?

No. It only prevents the default action. Developers must implement data processing or an API request separately.

Q7. Can preventDefault() be used on every event?

No. It only cancels default actions for cancelable events. Calling it on a non-cancelable event has no effect.

Q8. Why might a form not trigger its submit handler?

Native form validation may prevent submission when a field violates a constraint such as required or type="email". Other possible causes include a missing handler or incorrect form structure.

Q9. What does event.defaultPrevented indicate?

It indicates whether the event's default action has been prevented.

Q10. Is preventDefault() a React-only method?

No. It is part of the standard browser Event interface and is also available on React event objects.


16. Practice Exercises

  1. Create a React form that submits without reloading the page.
  2. Create an anchor link and prevent its default navigation when clicked.
  3. Build a registration form that reads values using FormData.
  4. Demonstrate the difference between preventDefault() and stopPropagation().
  5. Create a checkbox example that prevents its default toggle action.
  6. Handle the Enter key in an input using onKeyDown.
  7. Build a form that validates required fields and displays a success message.
  8. Create a custom search form that processes the entered search term.

17. Quick Revision Checklist

  • Understand default browser behaviour.
  • Know the purpose of event.preventDefault().
  • Practice preventing default form submission.
  • Understand how to intercept anchor navigation.
  • Learn how to access event properties.
  • Understand the difference between preventDefault() and stopPropagation().
  • Know that preventing default behaviour does not automatically save data.
  • Understand when default actions should be preserved.
  • Build practical React forms using event handlers.

18. Conclusion

Preventing Default Browser Behaviour is an important React JS concept that gives developers control over browser actions associated with events. The event.preventDefault() method is especially useful for handling forms, intercepting links, and implementing custom interactions. By understanding its purpose, limitations, and difference from stopPropagation(), developers can create interactive applications without accidentally disrupting expected browser behaviour.

Continue learning through JustAcademy React JS Training and explore the course through Register for React JS Course Demo.

Official References

whatsapp